package org.wannatrak.android.helper;

import android.app.*;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;
import org.wannatrak.android.ApplicationContext;
import org.wannatrak.android.R;
import org.wannatrak.android.activity.StartPageActivity;
import org.wannatrak.android.formatter.TimeFormatter;
import org.wannatrak.android.intf.ClickAction;
import org.wannatrak.android.intf.DialogAction;
import org.wannatrak.android.intf.Formatter;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;

/**
 * @Author: Maksim Tulupov maxtulupov@gmail.com
 * @Date: $Date: 2011-06-20 05:08:37 +0000 (Mon, 20 Jun 2011) $ 5:44 PM
 * @version: $Revision: 13 $
 * @id: $Id: DialogHelper.java 13 2011-06-20 05:08:37Z maxtulupov@gmail.com $
 */
public class DialogHelper {
    public static final int FROM_WIRELESS_SETTINGS = 1;
    public static final int FROM_LOCATION_SETTINGS = 2;

    private static final int TIME_DIALOG = 0;

    private static final int DATE_DIALOG = 1;

    public static Dialog createProgressDialog(Context context) {
        ProgressDialog dialog = new ProgressDialog(context);
        dialog.setMessage(context.getResources().getString(R.string.executing));
        dialog.setIndeterminate(true);
        dialog.setCancelable(true);
        return dialog;
    }

    public static void setTimeDialogToTextView(Context context, TextView textView, OnTimeSetListener onDateSetListener) {
        setDialogToTextView(context, textView, TIME_DIALOG, onDateSetListener);
    }

    public static void setDateDialogToTextView(Context context, TextView textView, OnDateSetListener onDateSetListener) {
        setDialogToTextView(context, textView, DATE_DIALOG, onDateSetListener);
    }

    public static void setTimeDialogToTextView(Context context, TextView textView) {
        setDialogToTextView(context, textView, TIME_DIALOG, null);
    }

    public static void setDateDialogToTextView(Context context, TextView textView) {
        setDialogToTextView(context, textView, DATE_DIALOG, null);
    }

    private static void setDialogToTextView(final Context context, final TextView textView, final int type,
                                            final OnSetListener onSetListener) {
        UIHelper.setActionToView(textView, new ClickAction() {
            public boolean actionPerformed(View view) {
                Formatter formatter;
                if (type == TIME_DIALOG) {
                    formatter = ApplicationContext.getFormatter(TimeFormatter.class);
                } else if (type == DATE_DIALOG) {
                    formatter = ApplicationContext.getFormatter(Date.class);
                } else {
                    throw new IllegalArgumentException(String.format("Unknown dialog type = %s", type));
                }
                Calendar c = Calendar.getInstance();
                try {
                    Object o = formatter.parse(textView.getText().toString());
                    if (o != null) {
                        c.setTime((Date) o);
                    }
                } catch (ParseException e) {
                    Log.e(getClass().getSimpleName(), "cant parse date = " + c, e);
                }
                final Dialog dialog;
                if (type == TIME_DIALOG) {
                    int defaultTime = 5;
                    if (textView.getText() != null) {
                        long i = WannatrakHelper.convertStringIntervalInMinutes(textView.getText().toString());
                        if (i > 0) {
                            defaultTime = (int) i;
                        }
                    }
                    TimeSetListenerImpl listener = new TimeSetListenerImpl(textView);
                    dialog = new TimePickerDialog(context,
                            listener,
                            0,
                            defaultTime,
                            true);
                    listener.setDialog(dialog, (OnTimeSetListener) onSetListener);
                } else if (type == DATE_DIALOG) {
                    DateSetListenerImpl listener = new DateSetListenerImpl(textView);
                    dialog = new DatePickerDialog(context,
                            listener,
                            c.get(Calendar.YEAR),
                            c.get(Calendar.MONTH),
                            c.get(Calendar.DAY_OF_MONTH));
                    listener.setDialog(dialog, (OnDateSetListener) onSetListener);
                } else {
                    throw new IllegalArgumentException(String.format("Unknown dialog type = %s", type));
                }
                dialog.show();
                return true;
            }
        });
    }

    public static AlertDialog getYesNoDialog(Activity activity, Drawable drawable, CharSequence title, CharSequence message,
                                             final DialogAction yesHandler,
                                             final DialogAction noHandler) {
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);

        if (drawable == null) {
            builder.setIcon(activity.getResources().getDrawable(android.R.drawable.ic_menu_help));
        } else {
            builder.setIcon(drawable);
        }

        if (!TextUtils.isEmpty(title)) {
            builder.setTitle(title);
        } else {
            builder.setTitle(activity.getResources().getString(R.string.confirmation));
        }

        if (!TextUtils.isEmpty(message)) {
            builder.setMessage(message);
        } else {
            builder.setMessage(activity.getResources().getString(R.string.would_like_continue));
        }

        builder.setPositiveButton(yesHandler.getNameCode(), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialogInterface, int i) {
                yesHandler.actionPerformed(dialogInterface, i);
            }
        });

        builder.setNegativeButton(noHandler.getNameCode(), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialogInterface, int i) {
                noHandler.actionPerformed(dialogInterface, i);
            }
        });

        return builder.create();
    }

    public static void showNoInternetDialog(final Activity activity, final DialogAction noHandler) {
        String title = activity.getResources().getString(R.string.no_internet_connection);
        String message = activity.getResources().getString(R.string.open_connection_settings);
        DialogAction yesHandler = new DialogAction() {

            public void actionPerformed(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
                activity.startActivityForResult(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS), FROM_WIRELESS_SETTINGS);
            }

            public int getNameCode() {
                return R.string.ok;
            }
        };

        DialogHelper.getYesNoDialog(activity, null, title, message, yesHandler, noHandler).show();
    }

    public static void showNoGpsDialog(final Activity activity) {
        String title = activity.getResources().getString(R.string.my_position);
        String message = activity.getResources().getString(R.string.location_services_off);
        DialogAction yesHandler = new DialogAction() {

            public void actionPerformed(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
                activity.startActivityForResult(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS), FROM_LOCATION_SETTINGS);
            }

            public int getNameCode() {
                return R.string.ok;
            }
        };
        DialogAction noHandler = new DialogAction() {

            public void actionPerformed(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }

            public int getNameCode() {
                return R.string.cancel;
            }
        };

        DialogHelper.getYesNoDialog(activity, null, title, message, yesHandler, noHandler).show();
    }

    private static class TimeSetListenerImpl implements TimePickerDialog.OnTimeSetListener {

        private Dialog dialog;
        private TextView textView;
        private OnTimeSetListener onTimeSetListener;

        private TimeSetListenerImpl(TextView textView) {
            this.textView = textView;
        }

        public void setDialog(Dialog dialog, OnTimeSetListener onTimeSetListener) {
            this.onTimeSetListener = onTimeSetListener;
            this.dialog = dialog;
        }

        public void onTimeSet(TimePicker timePicker, int hours, int minutes) {
            Formatter formatter = ApplicationContext.getFormatter(TimeFormatter.class);
            String time = formatter.format(DateHelper.getDate(0, 0, 0, hours, minutes));
            textView.setText(time);
            if (onTimeSetListener != null) {
                onTimeSetListener.onSet(timePicker, hours, minutes);
            }
            dialog.dismiss();
        }
    }

    private static class DateSetListenerImpl implements DatePickerDialog.OnDateSetListener {

        private Dialog dialog;
        private OnDateSetListener onDateSetListener;
        private TextView textView;

        private DateSetListenerImpl(TextView textView) {
            this.textView = textView;
        }

        public void setDialog(Dialog dialog, OnDateSetListener onDateSetListener) {
            this.onDateSetListener = onDateSetListener;
            this.dialog = dialog;
        }

        public void onDateSet(DatePicker datePicker, int year, int month, int day) {
            Formatter formatter = ApplicationContext.getFormatter(Date.class);
            String time = formatter.format(DateHelper.getDate(year, month, day));
            textView.setText(time);
            if (onDateSetListener != null) {
                onDateSetListener.onSet(datePicker, year, month, day);
            }
            dialog.dismiss();
        }
    }

    public interface OnSetListener {
    }

    public interface OnDateSetListener extends OnSetListener {
        void onSet(DatePicker datePicker, int year, int month, int day);
    }

    public interface OnTimeSetListener extends OnSetListener {
        void onSet(TimePicker timePicker, int hours, int minutes);
    }
}
